# Electoral Polls Balotage.
library(ggplot2)
library(tidyverse)
library(lubridate)
library(gridExtra)

ruta <- "C:/Users/Matias/Dropbox/Proyectos/Fondecyt Participacion Electoral/Articulos/Electoral Winners y Plebiscito/Harvard Dataverse/4. Replication Figure 1/"
load(paste0(ruta,"listado_encuestas_ic.Rdata"))

encs.pb2022 <- encs.pb2022 %>% mutate(Opcion = ifelse(Opcion == "Apruebo","Approve","Reject"))

encs.pb2022[c(4:6,8,9)] <- NULL

colnames(encs.pb2022)[4] <- "Porcentaje"
colnames(encs.pb2022)[5] <- "cimax"
colnames(encs.pb2022)[6] <- "cimin"

candidato <- c(rep("Boric",2),rep("Kast",2))
encuesta <- c(rep("Cadem",4))
porcentaje <- c(.52,.55,.48,.45)
fecha <- c("9-10 Dec 2021","15-16 Dec 2021",
           "9-10 Dec 2021","15-16 Dec 2021")

encuesta <- as.data.frame(cbind(candidato,porcentaje,encuesta,fecha))

pr <- ggplot(encuesta,aes(x=factor(fecha,levels = c("9-10 Dec 2021","15-16 Dec 2021")),
                    y=as.numeric(porcentaje),fill=candidato)) + geom_bar(stat="identity",position = "dodge2")+ 
  scale_y_continuous(labels = scales::percent, limits = c(0,1)) +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        strip.text.y = element_text(angle=0, size=13),
        plot.caption = element_text(size=11),
        panel.grid = element_line(color = "grey70",linetype = 2),
        legend.text = element_text(size=15),
        legend.title = element_text(size=15),
        legend.position = c(.9,.8),
        plot.title = element_text(size=20)) +
  labs(y="",x="Date",fill="Candidate",caption="",
       title = "A) Presidential election December 2021") 

pb <- ggplot(filter(encs.pb2022, Empresa %in% c("Cadem")),aes(x=Fecha,y=Porcentaje)) + 
  geom_line(aes(linetype=Opcion,color=Opcion),linewidth=1) +
  scale_x_date(date_breaks = "1 month", date_labels =  "%b") + theme_bw()  + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        strip.text.y = element_text(angle=0, size=13),
        plot.caption = element_text(size=11),
        panel.grid = element_line(color = "grey70",linetype = 2),
        axis.text.x = element_text(angle = 45),
        strip.text = element_text(size=13),
        legend.text = element_text(size=15),
        legend.title = element_text(size=15),
        legend.position = c(.9,.8),
        plot.title = element_text(size=20)) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
  scale_linetype_manual(values=c("dashed","solid")) +
  labs(caption="",
       color = "Option",linetype="Option",x="Date",y="",title = "B) Constitutional plebiscite September 2022")


ggsave(paste0(ruta,"Electoral Polls.png"),grid.arrange(pr,pb,nrow=2,heights=c(2,2)),
       width=25,height=25,units = "cm",
       dpi = 1000)

